<?php

include_once($mcrp . 'functions/cache.php');

class CategoryInfos
{
	var $title = 'Nouvelle catégorie';
	var $description = '';
	var $id = '-1';
}

function CreateCategory(&$CatInfos)
{
	global $mcsql;
	$result = $mcsql->Query('INSERT INTO categories(title, description) VALUES(\'' . addslashes($CatInfos->title) . '\', \'' . addslashes($CatInfos->description) . '\')');
	if($result === false) return false;
	$CatInfos = GetCategory($CatInfos->title, $CatInfos->description);
	ResetCacheParent('categorieslist');
	return true;
}

function GetCategory($Title, $Descr)
{
	global $mcsql;
	$answer = $mcsql->Query('SELECT * FROM categories WHERE title=\'' . $Title . '\' AND description=\'' . $Descr . '\'');
	if($cat = mysql_fetch_array($answer))
	{
		$ci = FillCategoryInfos($cat);
		return $ci;
	}
	return false;
}

function GetCategoryById($Id)
{
	global $mcsql;
	$answer = $mcsql->Query('SELECT * FROM categories WHERE id=\'' . $Id . '\'');
	if($cat = mysql_fetch_array($answer))
	{
		$ci = FillCategoryInfos($cat); 
		return $ci;
	}
	return false;
}

function GetAllCategories()
{
	global $mcsql;
	$categories = array();
	$answer = $mcsql->Query('SELECT * FROM categories');
	while($cat = mysql_fetch_array($answer))
	{
		$ci = FillCategoryInfos($cat);
		$categories[$cat['id']] = $ci;
	}
	return $categories;
}

function FillCategoryInfos($Cat)
{
	$ci = new CategoryInfos;
	$ci->title = $Cat['title'];
	$ci->description = $Cat['description'];
	$ci->id = $Cat['id'];
	return $ci;
}

function UpdateCategory($CatInfos)
{
	global $mcsql;
	$result = $mcsql->Query('UPDATE categories SET title=\'' . addslashes($CatInfos->title) . '\', description=\'' . addslashes($CatInfos->description) . '\' WHERE id=' . $CatInfos->id);
	ResetCacheParent('categorieslist');
	return $result;
}

function CategoryAddContest($CatId, $ContestId)
{
	$cat = GetCategoryById($CatId);
	if($cat === false) return false;
	$cat->contests[] = $ContestId;
	UpdateCategory($cat);
	return true;
}

function CategoryRemoveContest($CatId, $ContestId)
{
	$cat = GetCategoryById($CatId);
	$newcontests = array();
	if($cat === false) return false;
	foreach($cat->contests as $c)
	{
		if($c != $ContestId)
			$newcontests[] = $c;
	}
	$cat->contests = $newcontests;
	UpdateCategory($cat);
	return true;
}

function DeleteCategoryById($Id)
{
	global $mcsql;
	$mcsql->Query('DELETE FROM categories WHERE id=' . $Id);
	ResetCacheParent('categorieslist');
}